package com.zxcl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxcl.domain.SysUser;
import com.zxcl.domain.SysUserRole;
import com.zxcl.dto.PageDTO;
import com.zxcl.dto.SysUserAddDTO;
import com.zxcl.dto.SysUserQueryDTO;
import com.zxcl.dto.SysUserUpdateDTO;
import com.zxcl.ex.BusinessException;
import com.zxcl.mapper.SysUserMapper;
import com.zxcl.mapper.SysUserRoleMapper;
import com.zxcl.service.SysUserService;
import com.zxcl.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 分页查询用户
     * 1.如果shopId==1说明是超级店铺，可以查询所有员工
     * 否则只能查询自己店铺的员工
     *
     * @param pageDTO
     * @param userQueryDTO
     * @return
     */
    @Override
    public Page<SysUser> loadSysUserPage(PageDTO pageDTO, SysUserQueryDTO userQueryDTO) {
        //得到shopId
        Long shopId = AuthUtil.getShopId();
        //创建分页条件
        Page<SysUser> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        //查询
        Page<SysUser> userPage = this.getBaseMapper().selectPage(page, new LambdaQueryWrapper<SysUser>()
                .eq(!shopId.equals(1L), SysUser::getShopId, shopId) //如果shopId不等于1L（即!shopId.equals(1L)为真），则设置查询条件为匹配SysUser对象的shopId字段与shopId变量的值相等。
                //如果shopId等于1L（即!shopId.equals(1L)为假），则不设置该查询条件。
                .like(StringUtils.hasText(userQueryDTO.getUsername()), SysUser::getUsername, userQueryDTO.getUsername()) //它检查 userQueryDTO.getUsername() 是否有文本内容，如果满足条件，则使用 SysUser::getUsername 方法指定查询字段为 username，并使用 userQueryDTO.getUsername() 的值进行模糊匹配查询。
                //不满足就不设置查询条件
                .orderByDesc(SysUser::getCreateTime)
        );
        return userPage;
    }

    /**
     * 添加用户
     *
     * @param sysUserAddDTO
     * @return
     */
    @Override
    @Transactional  //事务
    public int addSysUser(SysUserAddDTO sysUserAddDTO) {
        Long userId = AuthUtil.getUserId();

        //验证用户是否存在
        SysUser sysUser = this.getBaseMapper().selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, sysUserAddDTO.getUsername()));
        if (!ObjectUtils.isEmpty(sysUser)) {
            System.out.println(sysUser.getUsername());
            throw new BusinessException("当前用户" + sysUserAddDTO.getUsername() + "已存在");
        }
        String password = sysUserAddDTO.getPassword();
        //加密设置
        sysUserAddDTO.setPassword(new BCryptPasswordEncoder().encode(password));
        //设置创建者id和时间, 不是在表单设置的那个
        sysUserAddDTO.setCreateUserId(userId);
        sysUserAddDTO.setCreateTime(new Date());
        //添加shopId
        sysUserAddDTO.setShopId(AuthUtil.getShopId());
        //保存用户
        int row = this.getBaseMapper().insert(sysUserAddDTO);

        //获取角色列表，表单是如此
        List<Long> roleIdList = sysUserAddDTO.getRoleIdList();
        //这里是sysUserid在mybatis添加时会自增
        Long addUserId = sysUserAddDTO.getUserId();
        //保存到用户角色关系表
        if (!CollectionUtils.isEmpty(roleIdList)) {
            for (Long roleId : roleIdList) {
                SysUserRole entity = new SysUserRole();
                entity.setUserId(addUserId);
                entity.setRoleId(roleId);
                sysUserRoleMapper.insert(entity);
            }
        }
        return row;
    }


    @Override
    @Transactional  //事务
    public int updateSysUser(SysUserUpdateDTO sysUserUpdateDTO) {
        Long userId = AuthUtil.getUserId();
        String password = sysUserUpdateDTO.getPassword();
        //加密设置
        sysUserUpdateDTO.setPassword(new BCryptPasswordEncoder().encode(password));
        //设置创建者id和时间, 不是在表单设置的那个
        sysUserUpdateDTO.setCreateUserId(userId);
        sysUserUpdateDTO.setCreateTime(new Date());
        //添加shopId
        sysUserUpdateDTO.setShopId(AuthUtil.getShopId());
        //保存用户
        int row = this.getBaseMapper().updateById(sysUserUpdateDTO);

        //获取角色列表，表单是如此
        List<Long> roleIdList = sysUserUpdateDTO.getRoleIdList();
        //这里是sysUserid在mybatis添加时会自增
        Long addUserId = sysUserUpdateDTO.getUserId();
        //保存到用户角色关系表
        if (!CollectionUtils.isEmpty(roleIdList)) {
            for (Long roleId : roleIdList) {
                SysUserRole entity = new SysUserRole();
                entity.setUserId(addUserId);
                entity.setRoleId(roleId);
                sysUserRoleMapper.updateById(entity);
            }
        }

        return row;
    }
}
